﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Linq;
using System.Reflection.PortableExecutable;

namespace System.Net.Http
{
    /// <summary>
    /// 扩展
    /// </summary>
    public static class HttpClientExtersions
    {
        public static string GetCookieValue(this HttpResponseMessage responseMessage, string key)
        {
            string result = "";

            if (responseMessage.Headers.TryGetValues("Set-Cookie", out var values))
            {
                foreach (var value in values)
                {
                    if (!string.IsNullOrEmpty(value))
                    {
                        var parts = value.Split(',');

                        foreach (var part in parts)
                        {
                            var cookieParts = part.Split(';').Select(s => s.Trim()).ToArray();
                            if (cookieParts.Length == 0)
                                continue;

                            var nameValue = cookieParts[0].Split(new[] { '=' }, 2);
                            if (nameValue.Length != 2)
                                continue;

                            if (nameValue[0] != key)
                                continue;

                            result = nameValue[1];
                            break;

                            //// 可以在这里解析更多的属性，如 Domain, Path 等
                            //for (int i = 1; i < cookieParts.Length; i++)
                            //{
                            //    var attribute = cookieParts[i];
                            //    if (attribute.StartsWith("Domain=", StringComparison.OrdinalIgnoreCase))
                            //    {
                            //        // 解析 Domain
                            //    }
                            //    else if (attribute.StartsWith("Path=", StringComparison.OrdinalIgnoreCase))
                            //    {
                            //        // 解析 Path
                            //    }
                            //    // 处理其他属性...
                            //}
                        }
                    }
                }
            }

            return result;
        }
    }
}